package cn.ixinjiu.libraryMangement.controller;

import cn.ixinjiu.libraryMangement.entity.UserInfo;
import cn.ixinjiu.libraryMangement.service.IUserInfoService;
import cn.ixinjiu.libraryMangement.service.impl.UserInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Created by XinChen on 2023-05-08
 *
 * @TODO 登录逻辑处理
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private IUserInfoService userInfoService = new UserInfoServiceImpl();

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 设置编码格式
            req.setCharacterEncoding("utf-8");
            resp.setHeader("Content-Type", "text/html;charset=utf-8");
            // 获取登录类型
            String loginType = req.getParameter("loginType");
            // 获取用户登录参数
            String email = req.getParameter("email");
            String password = req.getParameter("password");
            UserInfo userInfo = userInfoService.login(email, password, Integer.parseInt(loginType));
            if (userInfo != null) { // 用户不为空，判断权限
                // 用户信息存储到session
                req.getSession().setAttribute("userInfo", userInfo);
                int role = userInfo.getRole();
                if (role == 0) {
                    resp.sendRedirect("/jsp/user/menu.jsp"); // 重定向到借阅书籍主页面
                } else if (role == 1) {
                    resp.sendRedirect("/jsp/admin/menu.jsp"); // 重定向到普通管理员菜单页面
                } else {
                    resp.sendRedirect("/jsp/systemAdmin/menu.jsp"); // 重定向到系统管理员菜单页面
                }
            } else { // 用户为空，没有该用户
                System.out.println("fail");
                resp.sendRedirect("/index.jsp");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
